<?php

namespace app\mini\controller\salesman;

use app\common\controller\ApiController;
use app\common\enum\purchase\CheckStatus;
use app\common\enum\purchase\CheckType;
use app\common\model\DealerGoods;
use app\common\model\DealerGoodsSpec;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\CheckStock;
use app\company\model\CheckStock as CheckStockModel;
use app\company\model\CheckStockDetail;
use app\mini\model\Salesman;
use app\Request;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="盘点管理")
 */
class Stock extends ApiController
{
    private CheckStockDetail $detail_model;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new CheckStock();
        $this->detail_model = new CheckStockDetail();
    }

    public function list(): Json
    {
        $get  = $this->request->get();
        $where = [
            ['salesman_id', '=', $this->uid],
        ];
        if(empty($get['check_status'])) {
            $where[] = ['check_status', '=', CheckStatus::WAIT];
        }else{
            $where[] = ['check_status', '=', $get['check_status']];
        }
//        $list = $this->model->with(['detail', 'create_user', 'check_user'])
        $list = $this->model->with(['create_user', 'check_user'])
            ->where($where)
            ->where($this->defaultWhere)->order($this->sort)
            ->paginate($get['limit'] ?? 15)->each(function ($item){
                // 盘盈数量
                $item->py_num = $item->detail()->where('diff_num','>',0)->sum('diff_num');
                // 盘盈金额
                $item->py_money = $item->detail()->where('diff_num','>',0)->sum('diff_price');
                $item->py_color = 'rgba(90, 159, 244, 1)';
                // 盘亏数量
                $item->pk_num = $item->detail()->where('diff_num','<',0)->sum('diff_num');
                // 盘亏金额
                $item->pk_money = $item->detail()->where('diff_num','<',0)->sum('diff_price');
                $item->pk_color = 'rgba(245,108, 108, 1)';
                $doneCount = $item->detail()->where('check_status','=',2)->count();
                $totalCount = $item->detail()->count();
//                $item->check_status_text = $doneCount ? ($doneCount == $totalCount ? '全部完成' : '进行中' ) : '暂未开始';
                $item->check_status_text = $item->check_status == 1 ? '未完成' : '已完成';
                $item->check_type_text = $item->check_type == 1 ? '全盘' : '品类盘';
                $item->rate = $doneCount . '/' . $totalCount;
            });
        return $this->success($list);
    }

    public function detail($id): Json
    {
        $get  = $this->request->get();
        $where = [];
        if(empty($get['check_status'])) {
            $where[] = ['check_status', '=', CheckStatus::WAIT];
        }else{
            $where[] = ['check_status', '=', $get['check_status']];
        }
        $list = $this->detail_model->with([
            'goods' => function ($query) use ($get)
            {
                $query->field('id,name,image,code69')->with([
                    'spec'=>function ($query) {
                        $query->field('id,name,unit,dealer_goods_id,ratio,sale_price,unit_type');
                    }
                ])->withTrashed();
            },
//            'spec'  => function ($query)
//            {
//                $query->field('id,name,unit,image,sku')->withTrashed();
//            },
        ])
            ->field('CheckStockDetail.id,check_stock_id,dealer_goods_id,dealer_goods_spec_id,num,check_num,CheckStockDetail.remark,
            CheckStockDetail.create_time,CheckStockDetail.diff_num,CheckStockDetail.diff_price,check_status')
            ->where('check_stock_id', $id)->where($where)
            ->hasWhere('goods',function ($goods) use ($get){
                if(!empty($get['goods_name'])) $goods->where('name','like','%'.$get['goods_name'].'%');
            })
            ->paginate($get['limit'] ?? 15)->each(function ($item){
                $unit = '';
                $item->goods->spec->each(function ($vo) use (&$unit){
                    if($vo->unit_type == 1) $unit = $vo->unit;
                });
                $unit = $unit??'瓶';
                $item->num = $item->num.$unit;
                $item->color = $item->diff_num >= 0 ? ($item->diff_num > 0 ? 'rgba(90, 159, 244, 1)' : 'rgba(0, 0, 0, 1)' ) : 'rgba(245,108, 108, 1)';
            });
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="盘点")
     * @param Request $request
     * @return Json
     */
    public function modify(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
            'id' => 'require',
        ];
        $this->validate($post, $rule);
        $info = $this->detail_model->find($post['id']);
        $details = $post['spec'];
        $stock = 0;
        foreach ($details as $spec){
            if(empty($spec['num'])) $spec['num'] = 0;
            $stock += $spec['num'] * $spec['ratio'];
        }
//        if($post['check_num'] == '') $post['check_num'] = 0;
        $specInfo = (new DealerGoodsSpec())->where('dealer_goods_id',$post['dealer_goods_id'])->where('unit_type',1)->find();
        $diffNum = $stock - $info->num;
        $salePrice = $specInfo->sale_price !== null ?  $specInfo->sale_price : "1";
        $diffPrice =  bcmul($diffNum, $salePrice, 2);
        $this->detail_model->where('id', $post['id'])->save(['check_num' => $stock, 'diff_num' => $diffNum, 'diff_price' => $diffPrice,'check_status'=>CheckStock::CHECK_STATUS_YES]);
        return $this->success('修改成功');
    }

    /**
     * @NodeAnnotation(title="审核盘点")
     * @param Request $request
     * @return Json
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function check(Request $request): Json
    {
        // 每次失去焦点就调一次方法修改盘点单数量，最后统一改库存和盘点表状态
        // 或者是审核一次性更新盘点单数量、更新库存、盘点表状态
        $this->checkPost();
        $post      = $request->post();
        $checkInfo = $this->model->with('detail')->find($post['id']);
        if (!$checkInfo || $checkInfo->check_status != CheckStatus::WAIT) {
            return $this->error('盘点单不符合审核！');
        }
        foreach ($checkInfo->detail as $detail) {
            // 遍历修改商品库存
            (new DealerGoodsSpec())->where('id', $detail->dealer_goods_spec_id)->save(['stock' => $detail->check_num]);
        }
        // 修改盘点单状态
        (new CheckStockModel())->where('id', $post['id'])->save(['check_status' => CheckStatus::DONE, 'check_user_id' => $this->uid, 'check_time' => time()]);
        return $this->success('盘点成功');
    }

}